﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace SqliteWrapper.Procedures
{
    public class Proc_UpdateAlbum : IProcedure
    {
        private bool _reissue;

        public Proc_UpdateAlbum(bool reIssue)
        {
            _reissue = reIssue;
        }

        public override SqliteError doProcedure(object DataSource, string DBPath)
        {
            Album album =  DataSource as Album;
            SqliteError error = new SqliteError(){ErrorText = null,IsProcessSuccess = false};
            SqliteConnectionManager manager = SqliteConnectionManager.Create(DBPath);
            using(SQLiteWriteLock writeLock = new SQLiteWriteLock(manager.ConnectionString))
            {
                using(SQLiteConnection conn = manager.GetSqliteConnection())
                {
                    conn.Open();
                    using(SQLiteCommand cmd = conn.CreateCommand())
                    {
                        cmd.CommandText = "update Album set Title = @Title,CreateTimeTag = @CreateTimeTag,Desc = @Desc,Thumbnail = @Thumbnail where ID = @ID";
                        cmd.Parameters.Add("@ID", System.Data.DbType.Int64).Value = album.ID;
                        cmd.Parameters.Add("@Title", System.Data.DbType.String).Value = album.Title;
                        cmd.Parameters.Add("@CreateTimeTag", System.Data.DbType.String).Value = _reissue 
                                                                                                ? album.CreateTimeTag 
                                                                                                : DateTime.Now.ToString("yyyy-MM-dd");
                        cmd.Parameters.Add("@Desc", System.Data.DbType.String).Value = album.Desc;
                        cmd.Parameters.Add("@Thumbnail", System.Data.DbType.String).Value = album.Thumbnail; 
                        cmd.CommandType = System.Data.CommandType.Text;
                        try
                        {
                            cmd.ExecuteNonQuery();
                            error.IsProcessSuccess = true;
                        }
                        catch(Exception ex)
                        {
                            error.ErrorText = ex.Message;
                        }
                    }
                }
            }
            return error;
        }
    }
}
